package a;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public final class XEComERFetcher extends ExchangeRateFetcher {
	private final DecimalFormat df = new DecimalFormat("#,###.#");

	@Override
	public void fetch() {
		try {
			String queryUrl=String.format(
			"http://www.xe.com/ict/?basecur=USD&historical=false&year=%d&month=%d&day=%d&sort_by=code",2011,9,7);
			Document doc = Jsoup.connect(queryUrl).timeout(60000).userAgent("Mozilla/5.0 (Windows NT 6.1; rv:6.0.1) Gecko/20100101 Firefox/6.0.1").get();

			Iterator<Element> rateLines = doc.select("#home_main #content_left center table.tbl_sub tr").iterator();
			Element e;
			Elements n;
			while(rateLines.hasNext()&&(e=rateLines.next())!=null) {
				if((e.hasClass("row1")||e.hasClass("row2"))
						&&(n=e.children()).size()==4) {
					try {
						this.setRate(n.get(0).text().trim(), df.parse(n.get(2).text()).floatValue(),"USD");
					} catch (ParseException pe) {
						System.out.println("Unknown format:\""+n.toString()+"\"");
						continue;
					}
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
